package com.mh.study.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author MH
 * @since 2022-02-21
 */
@Slf4j
@RestController
@RequestMapping("auto-delivery")
public class AutoDeliveryController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/check-state/{userId}")
    public Integer checkState(@PathVariable String userId) {
        // 1545132
        List<ServiceInstance> instances = discoveryClient.getInstances("service-resume");
        ServiceInstance serviceInstance = instances.get(0);
        serviceInstance.getHost();
        String url = String.format("http://%s:%s/resume/open-state/%s",
                serviceInstance.getHost(), serviceInstance.getPort(), userId);
        return restTemplate.getForObject(url, Integer.class);
    }

    @GetMapping("/get-resume-port")
    public Integer getResumePort() {
        return restTemplate.getForObject("http://service-resume/resume/get-port", Integer.class);
    }

    @GetMapping("/get-resume-port-2")
    @HystrixCommand(threadPoolKey = "getResumePort2", fallbackMethod = "myFallBack",
            threadPoolProperties = {@HystrixProperty(name = "maxQueueSize", value = "20")},
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000"),
                    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "8000"),
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "3000")
            })
    public Integer getResumePort2() {
        // 这里注意把上面的hystrixCommand注掉，异步是获取不到的
        Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
        log.info("details={}", details);
        return restTemplate.getForObject("http://service-resume/resume/get-port-2", Integer.class);
    }

    public Integer myFallBack() {
        return -1;
    }
}
